<?php 
class Jobs extends CI_Model {
	public function __construct() {
		if (!defined("JOB_STATUS_0")) define("JOB_STATUS_0", 'Awaiting Quotation');
		if (!defined("JOB_STATUS_1")) define("JOB_STATUS_1", 'Price quoted');
		if (!defined("JOB_STATUS_2")) define("JOB_STATUS_2", 'Offer accepted (awaiting advance payment)');
		if (!defined("JOB_STATUS_3")) define("JOB_STATUS_3", 'Offer accepted (price part paid)');
		if (!defined("JOB_STATUS_4")) define("JOB_STATUS_4", 'Awaiting Job Execution');
		if (!defined("JOB_STATUS_5")) define("JOB_STATUS_5", 'Waiting for payment');
		if (!defined("JOB_STATUS_6")) define("JOB_STATUS_6", 'Waiting to receive payment');
		if (!defined("JOB_STATUS_7")) define("JOB_STATUS_7", 'Job closed');
		if (!defined("JOB_STATUS_8")) define("JOB_STATUS_8", 'Cancelled');
		if (!defined("JOB_STATUS_9")) define("JOB_STATUS_9", 'Denied Offer');
		if (!defined("JOB_STATUS_10")) define("JOB_STATUS_10", 'Expired Offer');
		if (!defined("JOB_STATUS_11")) define("JOB_STATUS_11", 'Deleted by admin');
	}
	
	/**
	 * Job order
	 * Status:
	 * 0 - awaiting quotation
	 * 1 - quoted a price
	 * 2 - user accepted
	 * 3 - user paid
	 * 4 - payment accepted
	 * 5 - job done, waiting for payment
	 * 6 - job done, paid everything
	 * 7 - job done, payment accepted, job closed
	 * 8 - Cancelled
	 * 9 - denied offer
	 * 10 - expired offer
	 * 
	 * @param int $owner
	 * @param string $moreinfo
	 * @param int $type
	 * @param int $draft
	 */
	public function jobOrder($owner, $moreinfo, $type, $draft = 0) {
		if (($type < 0) || ($type > 3)) {
			if ($type == 'term') {
				$type = 2;
			} elseif ($type == 'trip') {
				$type = 0;
			} elseif ($type == 'time') {
				$type = 1;
			} elseif ($type == 'upload') {
				$type = 3;
			}
		}
		$data = array(
			'owner_id' => $owner,
			'sessid' => $this->session->userdata('session_id'),
			'create_date' => date("Y-m-d H:i:s", time()),
			'moreinfo' => $moreinfo,
			'type' => $type,
			'status' => 0,
			'draft' => $draft
		);
		$this->db->insert('job_group', $data);
		$gid = $this->db->insert_id();
		
		if ($type == 0 || $type == 1) {
			$jobType = 4;
		} else {
			$jobType = $type;
		}
		
		$jobs = $this->getJobs($owner, $jobType);
		foreach ($jobs as $job) {
			$updateData = array(
				'belongs' => $gid,
			);
			
			$this->db->where('id', $job->id);
			$this->db->update('jobs', $updateData); 
		}
		
		return $gid;
	}
	
	/**
	 * Get oncoming job orders for user
	 * 
	 * @param $uid
	 */
	public function getOncoming($uid = -1, $count = false) {
		$return = array();
		
		// Job orders
		if ($uid < 0) {
			$sql = "SELECT * FROM `job_group` WHERE `status` >= 1 AND `status` <= 4 AND `owner_id` > 0 AND `draft` = 0 ORDER BY `gid` DESC";
			
			if ($count)
				$sql = "SELECT COUNT(*) AS `total` FROM `job_group` WHERE `status` >= 1 AND `status` <= 4 AND `owner_id` > 0 AND `draft` = 0";
		} else {
			$sql = "SELECT * FROM `job_group` WHERE `owner_id` = ".$uid." AND `status` < 5 AND `draft` = 0 ORDER BY `gid` DESC";
			
			if ($count)
				$sql = "SELECT COUNT(*) AS `total` FROM `job_group` WHERE `owner_id` = ".$uid." AND `status` < 5 AND `draft` = 0";
		}
		$query = $this->db->query($sql);
		$jobs = $query->result();
		
		if (!$count) {
			foreach ($jobs as $job) {
				$routes = $this->getOrderJobs($job->gid);
				$return[] = array('order' => $job, 'routes' => $routes);
			}
		}
		
		if ($count) {
			return $jobs[0]->total;
		}
		
		return $return;
	}
	
	public function setMessage($jid, $to, $level) {
		if ($to != 0 && $to != 1) $to = 0;
		
		if ($level == 0) {
			$updateData = array(
				'muser' => $to
			);
		} else {
			$updateData = array(
				'madmin' => $to
			);
		}
		
		$this->db->where('gid', $jid);
		$this->db->update('job_group', $updateData); 
	}
	
	/**
	 * Get completed job orders for user
	 * 
	 * @param $uid
	 */
	public function getCompleted($uid = -1) {
		$return = array();
		
		// Job orders
		if ($uid < 0) {
			$sql = "SELECT *, DATE_FORMAT(`create_date`, '%e %b %Y') AS `date` FROM `job_group` WHERE `status` = 7 AND `owner_id` > 0 ORDER BY `gid` DESC";
		} else {
			$sql = "SELECT *, DATE_FORMAT(`create_date`, '%e %b %Y') AS `date` FROM `job_group` WHERE `owner_id` = ".$uid." AND `status` = 7 ORDER BY `gid` DESC";
		}
		$query = $this->db->query($sql);
		$jobs = $query->result();
		
		foreach ($jobs as $job) {
			$routes = $this->getOrderJobs($job->gid);
			$return[] = array('order' => $job, 'routes' => $routes);
		}
		
		return $return;
	}
	
	/**
	 * Get cancelled job orders for user
	 * 
	 * @param $uid
	 */
	public function getCancelled($uid = -1) {
		$return = array();
		
		// Job orders
		if ($uid < 0) {
			$sql = "SELECT *, DATE_FORMAT(`create_date`, '%e %b %Y') AS `date` FROM `job_group` WHERE `status` > 7 AND `owner_id` > 0 ORDER BY `gid` DESC";
		} else {
			$sql = "SELECT *, DATE_FORMAT(`create_date`, '%e %b %Y') AS `date` FROM `job_group` WHERE `owner_id` = ".$uid." AND `status` > 7 ORDER BY `gid` DESC";
		}
		$query = $this->db->query($sql);
		$jobs = $query->result();
		
		foreach ($jobs as $job) {
			$routes = $this->getOrderJobs($job->gid);
			$return[] = array('order' => $job, 'routes' => $routes);
		}
		
		return $return;
	}
	
	/**
	 * Get drafts for user
	 * 
	 * @param $uid
	 */
	public function getDrafts($uid = -1) {
		$return = array();
		
		// Job orders
		if ($uid < 0) {
			$sql = "SELECT *, DATE_FORMAT(`create_date`, '%e %b %Y') AS `date` FROM `job_group` WHERE `draft` = 1 AND `owner_id` > 0 ORDER BY `gid` DESC";
		} else {
			$sql = "SELECT *, DATE_FORMAT(`create_date`, '%e %b %Y') AS `date` FROM `job_group` WHERE `owner_id` = ".$uid." AND `draft` = 1 ORDER BY `gid` DESC";
		}
		$query = $this->db->query($sql);
		$jobs = $query->result();
		
		foreach ($jobs as $job) {
			$routes = $this->getOrderJobs($job->gid);
			$return[] = array('order' => $job, 'routes' => $routes);
		}
		
		return $return;
	}
	
	/**
	 * Get jobs that needs quote
	 * 
	 * @param $uid
	 */
	public function getNeedQuote($uid = -1, $count = false) {
		$return = array();
		
		// Job orders
		if ($uid < 0) {
			$sql = "SELECT * FROM `job_group` WHERE `status` = 0 AND `owner_id` > 0 AND `draft` = 0 ORDER BY `gid` DESC";
			
			if ($count)
				$sql = "SELECT COUNT(*) AS `total` FROM `job_group` WHERE `status` = 0 AND `owner_id` > 0 AND `draft` = 0";
		} else {
			$sql = "SELECT * FROM `job_group` WHERE `owner_id` = ".$uid." AND `status` = 0 AND `draft` = 0 ORDER BY `gid` DESC";
		}
		$query = $this->db->query($sql);
		$jobs = $query->result();
		
		if (!$count) {
			foreach ($jobs as $job) {
				$routes = $this->getOrderJobs($job->gid);
				$jarr = array('order' => $job, 'routes' => $routes);
				
				if ($uid < 0) {
					$user =& Users::getInstance();
					
					$jarr['userinfo'] = $user->getUserInfo($job->owner_id);
				}
				
				$return[] = $jarr;
			}
		}
		
		if ($count) {
			return $jobs[0]->total;
		}
		
		return $return;
	}
	
	
	/**
	 * Get jobs that are waiting for confirmation
	 * 
	 * @param $uid
	 */
	public function getNeedConfirm($uid = -1, $count = false) {
		$return = array();
		
		// Job orders
		if ($uid < 0) {
			$sql = "SELECT * FROM `job_group` WHERE `status` = 1 AND `owner_id` > 0 ORDER BY `gid` DESC";
			
			if ($count)
				$sql = "SELECT COUNT(*) AS `total` FROM `job_group` WHERE `status` = 1 AND `owner_id` > 0";
		} else {
			$sql = "SELECT * FROM `job_group` WHERE `owner_id` = ".$uid." AND `status` = 1 ORDER BY `gid` DESC";
			
			if ($count)
				$sql = "SELECT COUNT(*) AS `total` FROM `job_group` WHERE `owner_id` = ".$uid." AND `status` = 1";
		}
		$query = $this->db->query($sql);
		$jobs = $query->result();
		
		if (!$count) {
			foreach ($jobs as $job) {
				$routes = $this->getOrderJobs($job->gid);
				$jarr = array('order' => $job, 'routes' => $routes);
				
				if ($uid < 0) {
					$user =& Users::getInstance();
					
					$jarr['userinfo'] = $user->getUserInfo($job->owner_id);
				}
				
				$return[] = $jarr;
			}
		}
		
		if ($count) {
			return $jobs[0]->total;
		}
		
		return $return;
	}
	
	public function getOrderJob($id) {
		$sql = "SELECT *, DATE_FORMAT(`create_date`, '%e %b %Y, %H:%i') AS `date` FROM `job_group` WHERE `gid` = ".$id;
		$query = $this->db->query($sql);
		
		return $query->row();
	}
	
	public function getOrderJobs($id) {
		$sql = "SELECT *, YEAR(`start_date`) AS `y`, MONTH(`start_date`) AS `m`, DAY(`start_date`) AS `d`, HOUR(`start_date`) AS `h`, MINUTE(`start_date`) AS `mi`, YEAR(`end_date`) AS `ey`, MONTH(`end_date`) AS `em`, DAY(`end_date`) AS `ed`, HOUR(`end_date`) AS `eh`, MINUTE(`end_date`) AS `emi` FROM `jobs` WHERE `belongs` = ".$id." ORDER BY `id` DESC";
		$query = $this->db->query($sql);
		
		return $query->result();
	}
	
	public function updatePrice($id, $price, $tax, $discount, $preq, $terms, $pmethods, $updateStatus = -1) {
		$data = array(
			'price' => $price,
			'tax' => $tax,
			'discount' => $discount,
			'preq' => $preq,
			'terms' => $terms,
			'pmethods' => $pmethods
		);
		
		if ($updateStatus >= 0) {
			$this->changeStatus($id, $updateStatus);
		}
		
		$this->db->where('gid', $id);
		$this->db->update('job_group', $data); 
	}
	
	public function setEndDate($id, $duration, $invalid) {
		$this->db->where('belongs', $id);
		$this->db->order_by("start_date", "asc");
		$this->db->limit(1);
		$q = $this->db->get('jobs');
		$job = $q->row();
		
		$sql = "UPDATE `job_group` SET `invalid` = '".$invalid."', `start_date` = '".$job->start_date."', `end_date` = ADDDATE('".$job->start_date."', INTERVAL ".(int)$duration." DAY) WHERE `gid` = ".(int)$id;
		$this->db->query($sql);
	}
	
	public function getDuePrice($id) {
		$sql = "SELECT SUM(`price`-`paid`) AS `total` FROM `job_group` WHERE `owner_id` = ".(int)$id." AND NOW() BETWEEN ADDDATE(`end_date`, INTERVAL 7 DAY) AND ADDDATE(`end_date`, INTERVAL 14 DAY)";
		$q = $this->db->query($sql);
		$res = $q->row();
		
		if ($res->total > 0) {
			return $res->total;
		}
		
		return 0;
	}
	
	public function getDuePriceList($id = 0) {
		if ($id > 0)
			$sql = "SELECT *, ADDDATE(`end_date`, INTERVAL 7 DAY) AS `duedate` FROM `job_group` WHERE `owner_id` = ".(int)$id." AND NOW() BETWEEN ADDDATE(`end_date`, INTERVAL 7 DAY) AND ADDDATE(`end_date`, INTERVAL 14 DAY)";
		else
			$sql = "SELECT *, ADDDATE(`end_date`, INTERVAL 7 DAY) AS `duedate` FROM `job_group` WHERE NOW() BETWEEN ADDDATE(`end_date`, INTERVAL 7 DAY) AND ADDDATE(`end_date`, INTERVAL 14 DAY)";
		$q = $this->db->query($sql);
		$jobs = $q->result();
		$return = array();
		foreach ($jobs as $job) {
				$routes = $this->getOrderJobs($job->gid);
				$jarr = array('order' => $job, 'routes' => $routes);
				
				$user =& Users::getInstance();
				
				$jarr['userinfo'] = $user->getUserInfo($job->owner_id);
				
				$return[] = $jarr;
			}
		
		return $return;
	}
	
	public function getOverduePrice($id) {
		$sql = "SELECT SUM(`price`-`paid`) AS `total` FROM `job_group` WHERE `owner_id` = ".(int)$id." AND NOW() > ADDDATE(`end_date`, INTERVAL 14 DAY)";
		$q = $this->db->query($sql);
		$res = $q->row();
		
		if ($res->total > 0) {
			return $res->total;
		}
		
		return 0;
	}
	
	public function getOverduePriceList($id = 0) {
		if ($id > 0)
			$sql = "SELECT *, ADDDATE(`end_date`, INTERVAL 7 DAY) AS `duedate` FROM `job_group` WHERE `owner_id` = ".(int)$id." AND NOW() > ADDDATE(`end_date`, INTERVAL 14 DAY)";
		else
			$sql = "SELECT *, ADDDATE(`end_date`, INTERVAL 7 DAY) AS `duedate` FROM `job_group` WHERE NOW() > ADDDATE(`end_date`, INTERVAL 14 DAY)";
		$q = $this->db->query($sql);
		$jobs = $q->result();
		$return = array();
		foreach ($jobs as $job) {
				$routes = $this->getOrderJobs($job->gid);
				$jarr = array('order' => $job, 'routes' => $routes);
				
				$user =& Users::getInstance();
				
				$jarr['userinfo'] = $user->getUserInfo($job->owner_id);
				
				$return[] = $jarr;
			}
		
		return $return;
	}
	
	public function getOverdueCount() {
		$sql = "SELECT `end_date` FROM `job_group` WHERE NOW() > ADDDATE(`end_date`, INTERVAL 14 DAY) AND (`price`-`paid`) > 0";
		$q = $this->db->query($sql);
		$res = $q->result();
		
		return count($res);;
	}
	
	public function changeStatus($id, $status) {
		$data = array('status' => $status);
		
		$this->db->where('gid', $id);
		$this->db->update('job_group', $data);
	}
	
	public function cancelOrder($id) {
		$data = array('cancel' => 1);
		
		$this->db->where('gid', $id);
		$this->db->update('job_group', $data);
	}
	
	public function setCancelFee($id, $fee) {
		if ($fee > 0) {
			$data = array('cancelfee' => $fee);
			
			$this->db->where('gid', $id);
			$this->db->update('job_group', $data);
		} else {
			$this->changeStatus($id, 8);
			
			$data = array('cancelfee' => 0);
			
			$this->db->where('gid', $id);
			$this->db->update('job_group', $data);
		}
	}
	
	public function setCancelPaid($id) {
		$data = array('cancelfeepaid' => 1);
		
		$this->db->where('gid', $id);
		$this->db->update('job_group', $data);
	}
	
	public function neededPayment($jid) {
		$sql = "SELECT * FROM `job_group` WHERE `gid` = ".$jid;
		$query = $this->db->query($sql);
		$job = $query->row();
		
		$total = ($job->price) + ($job->price * $job->tax/100) - ($job->price * $job->discount/100);
		
		if ($job->status < 4) { // new job, first payment
			/*if ($total > 500) {
				return $total/2;
			} else {
				return 0;
			}*/
			return $job->preq;
		} else { // second payment, after job completion
			$needed = $total - $job->paid;
			$needed = ($needed < 0) ? 0 : $needed;
			
			return $needed;
		}
	}
	
	public function addPayment($jid, $amount) {
		$sql = "UPDATE `job_group` SET `paid` = (`paid` + ".$amount.") WHERE `gid` = ".$jid;
		$this->db->query($sql);
	}
	
	/**
	 * Adds the job order to the database
	 * Type:
	 * 0 - trip based
	 * 1 - time based
	 * 2 - term based
	 * 3 - upload itinerary
	 * 
	 * @param array/object $params
	 */
	public function createJob($params) {
		$params['create_date'] = date("Y-m-d H:i:s", time());
		$params['sessionid'] = $this->session->userdata('session_id');
		
		$this->db->insert('jobs', $params);
		return $this->db->insert_id();
	}
	
	public function createTrip($date, $passangers, $from, $to, $return, $moreinfo, $owner, $draft = 0, $editId = 0) {
		$data = array(
			'start_date' => $date,
			'passangers' => $passangers,
			'from' => $from,
			'to' => $to,
			'return' => $return,
			'moreinfo' => $moreinfo,
			'draft' => $draft,
			'job_type' => 0,
			'owner_id' => $owner
		);
		
		if ($editId > 0) {
			$this->db->where('id', $editId);
			$this->db->update('jobs', $data);
			
			return $editId;
		}
		
		return $this->createJob($data);
	}
	
	public function createTime($date, $enddate, $passangers, $hours, $locations, $moreinfo, $owner, $draft = 0, $editId = 0) {
		$data = array(
			'start_date' => $date,
			'end_date' => $enddate,
			'passangers' => $passangers,
			'hours' => $hours,
			'locations' => $locations,
			'moreinfo' => $moreinfo,
			'draft' => $draft,
			'job_type' => 1,
			'owner_id' => $owner
		);
		
		if ($editId > 0) {
			$this->db->where('id', $editId);
			$this->db->update('jobs', $data);
			
			return $editId;
		}
		
		return $this->createJob($data);
	}
	
	public function createTerm($date, $moreinfo, $owner, $draft = 0) {
		$data = array(
			'start_date' => $date,
			'moreinfo' => $moreinfo,
			'draft' => $draft,
			'job_type' => 2,
			'owner_id' => $owner
		);
		
		return $this->createJob($data);
	}
	
	public function createUpload($filename, $ext, $filesize, $origname, $moreinfo, $owner, $draft = 0) {
		$data = array(
			'filename' => $filename,
			'ext' => $ext,
			'filesize' => $filesize,
			'origname' => $origname,
			'origid' => $owner,
			'moreinfo' => $moreinfo,
			'draft' => $draft,
			'job_type' => 3,
			'owner_id' => $owner
		);
		
		return $this->createJob($data);
	}
	
	public function formatPrice($price, $sign = true) {
		if ($sign)
			return 'S$ '. number_format($price, 2, '.', ',');
		else
			return number_format($price, 2, '.', ',');
	}
	
	/**
	 * Load jobs
	 * Type:
	 * all - all jobs
	 * 0-3 - choosen type
	 * 4 - time and trip based
	 * 
	 * @param $type
	 */
	public function getJobs($uid, $type = 'all') {
		if ($type != 'all') {
			if ($type == 4) {
				$addToSql = " AND (`job_type` = 0 OR `job_type` = 1)";
			} elseif ($type >= 0 && $type <= 3) {
				$addToSql = " AND `job_type` = ".$type;
			} else {
				$addToSql = "";
			}
		} else {
			$addToSql = "";
		}
		
		$sql = "SELECT *, `return` as `returnn`, YEAR(`start_date`) AS `y`, MONTH(`start_date`) AS `m`, DAY(`start_date`) AS `d`, HOUR(`start_date`) AS `h`, MINUTE(`start_date`) AS `mi`, YEAR(`end_date`) AS `ey`, MONTH(`end_date`) AS `em`, DAY(`end_date`) AS `ed`, HOUR(`end_date`) AS `eh`, MINUTE(`end_date`) AS `emi` FROM `jobs` WHERE `owner_id` = ".$uid." AND `sessionid` = '".$this->session->userdata('session_id')."'".$addToSql." AND `belongs` = 0 ORDER BY `id` DESC";
		$query = $this->db->query($sql);
		$jobs = $query->result();
		
		/*for ($i = 0; $i < count($jobs); $i++) {
			if ($jobs[$i]->job_type == "1") {
				unset($jobs[$i]->locations);
			}
		}*/
		
		return $jobs;
	}
	
	public function getJob($jid, $format = true) {
		$sql = "SELECT *, `return` as `returnn`, YEAR(`start_date`) AS `y`, MONTH(`start_date`) AS `m`, DAY(`start_date`) AS `d`, HOUR(`start_date`) AS `h`, MINUTE(`start_date`) AS `mi`, YEAR(`end_date`) AS `ey`, MONTH(`end_date`) AS `em`, DAY(`end_date`) AS `ed`, HOUR(`end_date`) AS `eh`, MINUTE(`end_date`) AS `emi` FROM `jobs` WHERE `id` = ".$jid;
		$query = $this->db->query($sql);
		
		$res = $query->row();
		if ($format)
			$res->{"formatted"} = $this->formatJobInfo($res);
		
		/*if ($res->job_type == "1") {
			unset($res->locations);
		}*/
		
		return $res;
	}
	
	public function delete($jid, $uid = null) {
		$data = array("id" => $jid);
		if ($uid != null) {
			$data['owner_id'] = $uid;
		}
		$this->db->delete('jobs', $data); 
	}
	
	public function changePrice($id, $reason, $amount) {
		$sql = "UPDATE `job_group` SET `price` = `price`".$amount." WHERE `gid` = ".$id;
		$this->db->query($sql);
		
		$data = array(
			'jid' => $id,
			'reason' => $reason,
			'amount' => $amount
		);
		$this->db->insert('price_changes', $data);
	}
	
	public function formatJobInfo($job, $showType = false) {
		$text = "";
		
		if ($job->job_type == 0) {
			// trip
			if ($showType)
				$text .= "Type: Trip Based\n";
			$text .= "Trip Date and Time: ".$job->start_date;
			$text .= "\nNumber of Passengers: ".$job->passangers;
			$text .= "\nFrom: ".htmlspecialchars($job->from);
			//$text .= "\nTo: ".htmlspecialchars($job->to);
			$locs = json_decode($job->to);
			$text .= "\nTo: ";
			if (is_array($locs)) {
				$iter = 0;
				foreach ($locs as $loc) {
					if ($iter > 0) $text .= "; ";
					$text .= htmlspecialchars($loc);
					
					$iter++;
				}
			}
			if (!empty($job->return))
				$text .= "\nReturn: ".htmlspecialchars($job->return);
		} elseif ($job->job_type == 1) {
			// time
			if ($showType)
				$text .= "Type: Time Based\n";
			$text .= "Start Date and Time: ".$job->start_date;
			$text .= "\nEnd Date and Time: ".$job->end_date;
			$text .= "\nNumber of Passengers: ".$job->passangers;
			$text .= "\nNumber of Hours: ".$job->hours;
			$locs = json_decode($job->locations);
			$text .= "\nLocations: ";
			if (is_array($locs)) {
				$iter = 0;
				foreach ($locs as $loc) {
					if ($iter > 0) $text .= "; ";
					$text .= htmlspecialchars($loc);
					
					$iter++;
				}
			}
		} elseif ($job->job_type == 2) {
			// term
			$text .= "Expected start date: ".$job->start_date;
		} elseif ($job->job_type == 3) {
			// itinerary
			$text .= anchor('/download/'.$job->id, $job->origname);
		}
		
		return $text;
	}
	
	/**
	 * Job order
	 * Status:
	 * 0 - awaiting quotation
	 * 1 - quoted a price
	 * 2 - user accepted
	 * 3 - user paid
	 * 4 - payment accepted
	 * 5 - job done, waiting for payment
	 * 6 - job done, paid everything
	 * 7 - job done, payment accepted, job closed
	 */
	function showActionLinks($job, $where) {
		$html = '';
		
		if ($where == "oncoming") {
			if ($job->status == 0) {
				if ($job->cancel != 1) {
					$html .= anchor_img('joborder/deny/'.$job->gid, 'title="Cancel this job order"', 'assets/images/icons/delete.png');
					$html .= ' '.anchor_img('/request/time-based/0/'.$job->gid, 'title="Edit"', 'assets/images/icons/edit.png');
				}
				$html .= ' '.anchor_img("joborder/".$job->gid."#actionForm", 'title="Send message"', 'assets/images/icons/contact.png');
				$html .= ' '.anchor_img("joborder/".$job->gid, 'title="View details"', 'assets/images/icons/view.png');
			} elseif ($job->status == 1) {
				if ($job->cancel != 1) {
					$html .= anchor_img('joborder/accept/'.$job->gid, 'title="Accept!"', 'assets/images/icons/yes.png');
					$html .= ' '.anchor_img('joborder/deny/'.$job->gid, 'title="Deny!"', 'assets/images/icons/no.png');
					$html .= ' '.anchor_img('/request/time-based/0/'.$job->gid, 'title="Edit"', 'assets/images/icons/edit.png');
				}
				$html .= ' '.anchor_img("joborder/".$job->gid."#actionForm", 'title="Send message"', 'assets/images/icons/contact.png');
				$html .= ' '.anchor_img("joborder/".$job->gid, 'title="View details"', 'assets/images/icons/view.png');
			} elseif ($job->status == 2) {
				if ($job->cancel != 1) {
					$html .= anchor_img('joborder/cancel/'.$job->gid, 'title="Cancel this job order"', 'assets/images/icons/delete.png');
					$html .= ' '.anchor_img("joborder/".$job->gid."#actionForm", 'title="Pay"', 'assets/images/icons/pay.png');
				}
				//$html .= ' '.anchor_img('/request/time-based/0/'.$job->gid, 'title="Edit"', 'assets/images/icons/edit.png');
				$html .= ' '.anchor_img("joborder/".$job->gid."#actionForm", 'title="Send message"', 'assets/images/icons/contact.png');
				$html .= ' '.anchor_img("joborder/".$job->gid, 'title="View details"', 'assets/images/icons/view.png');
			} elseif ($job->status == 3) {
				if ($job->cancel != 1) {
					$html .= anchor_img('joborder/cancel/'.$job->gid, 'title="Cancel this job order"', 'assets/images/icons/delete.png');
				}
				$html .= ' '.anchor_img("joborder/".$job->gid."#actionForm", 'title="Send message"', 'assets/images/icons/contact.png');
				$html .= ' '.anchor_img("joborder/".$job->gid, 'title="View details"', 'assets/images/icons/view.png');
			} elseif ($job->status == 4) {
				if ($job->cancel != 1) {
					$html .= anchor_img('joborder/cancel/'.$job->gid, 'title="Cancel this job order"', 'assets/images/icons/delete.png');
				}
				$html .= ' '.anchor_img("joborder/".$job->gid."#actionForm", 'title="Pay"', 'assets/images/icons/pay.png');
				$html .= ' '.anchor_img("joborder/".$job->gid, 'title="View details"', 'assets/images/icons/view.png');
			}
		} elseif ($where == "drafts") {
			$html .= anchor_img('joborder/delete/'.$job->gid, 'title="Delete draft"', 'assets/images/icons/delete.png');
			$html .= ' '.anchor_img('/request/time-based/0/'.$job->gid, 'title="Edit draft"', 'assets/images/icons/edit.png');
		} elseif ($where == "due" || $where == "overdue") {
			$html .= anchor_img("joborder/".$job->gid."#actionForm", 'title="Send message"', 'assets/images/icons/contact.png');
			$html .= ' '.anchor_img("joborder/".$job->gid."#actionForm", 'title="Pay"', 'assets/images/icons/pay.png');
		} elseif ($where == "completed") {
			$html .= anchor_img("joborder/reuse/".$job->gid, 'title="Reuse Job info and edit it to submit new request"', 'assets/images/icons/again.png');
			$html .= ' '.anchor_img("joborder/".$job->gid, 'title="View details"', 'assets/images/icons/view.png');
		} elseif ($where == "cancelled") {
			$html .= ' '.anchor_img("joborder/".$job->gid, 'title="View details"', 'assets/images/icons/view.png');
		}
		
		return $html;
	}
	
	/**
	 * Job order
	 * Status:
	 * 0 - awaiting quotation
	 * 1 - quoted a price
	 * 2 - user accepted
	 * 3 - user paid
	 * 4 - payment accepted
	 * 5 - job done, waiting for payment
	 * 6 - job done, paid everything
	 * 7 - job done, payment accepted, job closed
	 */
	function showAdminActionLinks($job, $where) {
		$html = '';
		
		if ($where == "oncoming") {
				$html .= anchor_img("joborder/".$job->gid."#actionForm", 'title="Send message"', 'assets/images/icons/contact.png');
				$html .= ' '.anchor_img("joborder/".$job->gid, 'title="View details"', 'assets/images/icons/view.png');
		} elseif ($where == "quote") {
			$html .= anchor_img('joborder/admdelete/'.$job->gid, 'title="Delete this job order"', 'assets/images/icons/delete.png');
			$html .= ' '.anchor_img("joborder/".$job->gid."#actionForm", 'title="Send message"', 'assets/images/icons/contact.png');
			$html .= ' '.anchor_img("joborder/".$job->gid, 'title="View details"', 'assets/images/icons/view.png');
			if ($job->type == "2") {
				$html .= ' '.anchor_img("ri/add/".$job->gid, 'title="Transform"', 'assets/images/icons/transform.png');
			} elseif ($job->type == "3") {
				$html .= ' '.anchor_img("request/time-based/0/".$job->gid, 'title="Transform"', 'assets/images/icons/transform.png');
			} else {
				$html .= ' '.anchor_img("joborder/".$job->gid."#actionForm", 'title="Quote"', 'assets/images/icons/quote.png');
			}
		} elseif ($where == "confirm") {
			$html .= anchor_img('joborder/admdelete/'.$job->gid, 'title="Delete this job order"', 'assets/images/icons/delete.png');
			$html .= ' '.anchor_img("joborder/".$job->gid."#actionForm", 'title="Send message"', 'assets/images/icons/contact.png');
			$html .= ' '.anchor_img("joborder/".$job->gid, 'title="View details"', 'assets/images/icons/view.png');
		} elseif ($where == "due") {
			$html .= anchor_img("joborder/".$job->gid."#actionForm", 'title="Send message"', 'assets/images/icons/contact.png');
		} elseif ($where == "completed") {
			$html .= anchor_img("joborder/".$job->gid, 'title="View details"', 'assets/images/icons/view.png');
		}
		
		return $html;
	}
	
	function deleteJobOrder($jid) {
		$data = array('gid' => $jid);
		$this->db->delete('job_group', $data);
		
		$data = array('belongs' => $jid);
		$this->db->delete('jobs', $data);
	}
	
	function duplicateJobs($jid) {
		$sql = "INSERT INTO `jobs` (`start_date`, `passangers`, `from`, `to`, `return`, `hours`, `locations`, `filename`, `ext`, `filesize`, `origname`, `origid`, `moreinfo`, `owner_id`, `sessionid`, `create_date`, `job_type`, `job_status`, `total_price`, `payment_due_date`, `payment_overdue`, `draft`) (SELECT `start_date`, `passangers`, `from`, `to`, `return`, `hours`, `locations`, `filename`, `ext`, `filesize`, `origname`, `origid`, `moreinfo`, `owner_id`, '".$this->session->userdata('session_id')."', NOW(), `job_type`, '0', `total_price`, '0', '0', `draft` FROM `jobs` WHERE `belongs` = ".$jid.")";
		$this->db->query($sql);
	}
	
	public function addInvoice($jid, $type, $fields, $proforma = 0) {
		$this->load->model('Chats');
		$user =& Users::getInstance();
		
		$partial = 0;
		
		if (!$proforma) {
			$pneed = $this->neededPayment($jid);
			
			if ($pneed > 0) $partial = 1;
		}
		
		$idata = array(
			'jid' => $jid,
			'type' => $type,
			'date' => date('Y-m-d'),
			'partial' => $partial,
			'fields' => $fields,
			'proforma' => $proforma
		);
		
		$this->db->insert('ainvoices', $idata);
		
		$inv = $this->db->insert_id();
		
		if (!$proforma) {
			$this->Jobs->setMessage($jid, 1, 0);
			
			$text = '<p>We have issued a new invoice on your order. You can see the invoice '.anchor('/invoices/view/'.$inv, 'here').'</p>';
			
			$this->Chats->post($jid, $user->id, $text, 6, 0, 0);
		}
		
		return $inv;
	}
	
	function createPDF($uinfo, $order, $type, $date, $invoice = null) {
		if ($invoice) {
			$type = $invoice->type;
			$date = $invoice->date;
		}
		require_once(FCPATH.'/tcpdf/config/lang/eng.php');
		require_once(FCPATH.'/tcpdf/tcpdf.php');
		
		// create new PDF document
		//$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
		$width = 500;  
		$height = 300; 
		$orientation = ($height>$width) ? 'P' : 'L';  
		/*$pdf->addFormat("custom", $width, $height);  
		$pdf->reFormat("custom", $orientation);*/
		$pagelayout = array($width, $height);
		$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, $pagelayout, true, 'UTF-8', false);
		
		// set document information
		$pdf->SetCreator(PDF_CREATOR);
		$pdf->SetAuthor('BookaBus Ltd.');
		$pdf->SetTitle('Invoice');
		$pdf->SetSubject('Invoice');
		$pdf->SetKeywords('BookaBus');
		
		// set header and footer fonts
		$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
		$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
		
		// set default monospaced font
		$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
		
		//set margins
		$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
		$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
		$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
		
		//set auto page breaks
		$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
		
		//set image scale factor
		$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
		
		//set some language-dependent strings
		$pdf->setLanguageArray($l);
		
		// ---------------------------------------------------------
		
		// set font
		$pdf->SetFont('dejavusans', '', 10);
		
		$pdf->AddPage();
		
		$clientname = $uinfo->name;
		if (!empty($uinfo->company)) $clientname .= ", ".$uinfo->company;
		
		$validity = "";
		$terms = "";
		
		if ($type == 1) $terms = '<b>TERMS:</b> '.$order->period.' months<br  />';
		else $validity = '<b>VALIDITY:</b> '.$order->invalid.'<br  />';
		
		if ($type == 0 || $type == 2) $order->id = $order->gid;
		
		$fieldsHTML = '';
		if (!empty($invoice->fields)) {
			$fields = json_decode($invoice->fields);
			
			foreach ($fields as $field) {
				$fieldsHTML .= '<b>'.$field->name.':</b> '.$field->value.'<br  />';
			}
		}
		
		$html = '<div align="center"><img src="'.FCPATH.'assets/images/bookabus.jpg" /></div><h1 align="center">Invoice'.(($invoice->proforma == 1) ? ' Proforma' : '').'</h1>

<table valign="top" cellpadding="10" cellspacing="0" border="1" bordercolor="#CCCCCC" align="left">	
	<tr bgcolor="#CCCCCC">
		<td valign="top"><b>TO</b></td>
		<td valign="top"><b>FROM</b></td>
		<td valign="top"><b>Details</b></td>
	</tr>
	<tr>
		<td valign="top">'.$clientname.'</td>
		<td valign="top">Book a Bus Pte Ltd</td>
		<td valign="top"></td>
	</tr>
	<tr>
		<td valign="top">'.$uinfo->email.'<br  />'.$uinfo->phone.'</td>
		<td valign="top">20 Bukit Batok Crescent<br  />09-07 Enterprise Centre<br  />Singapore 658080<br  />TEL: +65 6316 6350<br  />FAX: +65 6569 6166</td>
		<td valign="top">
			<b>DATE:</b> '.date('jS F Y', strtotime($date)).'<br  />
			<b>QUOTE ID:</b> '.$order->id.'<br  />
			<b>FOR:</b> Bus Services<br  />
			'.$terms.'
			'.$validity.'
			<b>REP:</b> Darren Lim<br  />
			<b>Mobile:</b> 94773707<br  />
			<b>e-mail:</b> darren@bookabus.sg<br  />
			'.$fieldsHTML.'
		</td>
	</tr>
</table>

<br />&nbsp;
<h1 align="center">Order Details</h1>

<table valign="top" cellpadding="10" cellspacing="0" border="1" bordercolor="#CCCCCC" align="left">
	<tr bgcolor="#CCCCCC">
		<td valign="top"'.(($type == 1) ? "" : ' width="55"').'><b>ITEM</b></td>
		<td valign="top"'.(($type == 1) ? "" : ' width="200"').'><b>DESCRIPTION</b></td>
		<td valign="top"><b>DATE (TIME)</b></td>
		<td valign="top"><b>BUS TYPE</b></td>
		<td valign="top"><b>'.(($type == 1) ? "AMOUNT, PER MONTH, SGD" : 'AMOUNT, SGD').'</b></td>
	</tr>';
		
		if ($type == 1) {
			//recurring
			$routes = json_decode($order->routes);
			$c = 1;
			foreach ($routes as $route) {
				for ($i = 0; $i < count($route->weekdays); $i++) {
					$route->weekdays[$i] = substr($route->weekdays[$i], 0, 2);
				}
				$html .= '<tr>
					<td valign="top">'.$c.'</td>
					<td valign="top">'.implode(', ', $route->weekdays).'</td>
					<td valign="top"></td>
					<td valign="top">'.$route->bustype.'</td>
					<td valign="top"></td>
				</tr>';
				
				// locations
				foreach ($route->pickup as $pickup) {
					$html .= '<tr>
						<td valign="top"></td>
						<td valign="top">Pickup Location: '.$pickup->location.'</td>
						<td valign="top">'.$pickup->time.'</td>
						<td valign="top"></td>
						<td valign="top"></td>
					</tr>';
				}
				foreach ($route->dropoff as $dropoff) {
					$html .= '<tr>
						<td valign="top"></td>
						<td valign="top">Drop Off Location: '.$dropoff->location.'</td>
						<td valign="top">'.$dropoff->time.'</td>
						<td valign="top"></td>
						<td valign="top"></td>
					</tr>';
				}
				
				$html .= '<tr>
					<td valign="top"></td>
					<td valign="top"></td>
					<td valign="top"></td>
					<td valign="top">Total (Item '.$c.')</td>
					<td valign="top">'.number_format($route->price, 2, '.', ',').'</td>
				</tr>';
				
				$c++;
			}
			
			$html .= '<tr>
				<td valign="top"></td>
				<td valign="top"></td>
				<td valign="top"></td>
				<td valign="top"><b>Grand Total:</b></td>
				<td valign="top"><b>'.number_format($order->total_price, 2, '.', ',').'</b></td>
			</tr>';
		} elseif ($type == 2) { // cancellation fee
			$html .= '<tr>
					<td valign="top">1</td>
					<td valign="top">Cancelation fee</td>
					<td valign="top"></td>
					<td valign="top"></td>
					<td valign="top">'.number_format($order->cancelfee, 2, '.', ',').'</td>
				</tr>';
			
			$html .= '<tr>
				<td valign="top"></td>
				<td valign="top"></td>
				<td valign="top"></td>
				<td valign="top"><b>Grand Total:</b></td>
				<td valign="top"><b>'.number_format($order->cancelfee, 2, '.', ',').'</b></td>
			</tr>';
		} else {
			// jobs
			$c = 0;
			$j = $this->getOrderJobs($order->gid);
			foreach ($j as $job) {
				$c++;
				if ($job->job_type == 0 || $job->job_type == 1) {
					$html .= '<tr>
						<td valign="top">'.$c.'</td>
						<td valign="top">'.nl2br($this->Jobs->formatJobInfo($job)).'</td>
						<td valign="top">'.(($job->job_type == 1) ? "Time Based" : "Trip Based").'</td>
						<td valign="top"></td>
						<td valign="top"></td>
					</tr>';
				}
			}
			
			// Price changes
			//if ($invoice->proforma != 1) {
				$this->db->where('jid', $order->gid);
				$qc = $this->db->get('price_changes');
				$changes = $qc->result();
				foreach ($changes as $change) {
					$reason = ($change->amount{0} == "-") ? "Price decrease: " : "Price increase: ";
					$reason .= $change->reason;
					$html .= '<tr>
						<td valign="top">'.$c.'</td>
						<td valign="top">'.$reason.'</td>
						<td valign="top"></td>
						<td valign="top"></td>
						<td valign="top">'.number_format(str_replace(array('-', '+'), '', $change->amount), 2, '.', ',').'</td>
					</tr>';
					
					$c++;
				}
			//}
			
			if ($type == 1) {
				$html .= '<tr>
					<td valign="top"></td>
					<td valign="top"></td>
					<td valign="top"></td>
					<td valign="top"><b>Grand Total:</b></td>
					<td valign="top"><b>'.number_format($order->price + ($order->price*$order->tax/100) - ($order->price*$order->discount/100), 2, '.', ',').'</b></td>
				</tr>';
			} else {
				$total = $order->price;
				$grandtotal = $order->price + ($order->price*$order->tax/100) - ($order->price*$order->discount/100);
				$paid = $order->paid;
				$html .= '<tr>
					<td valign="top"></td>
					<td valign="top"></td>
					<td valign="top"></td>
					<td valign="top"><b>Total:</b></td>
					<td valign="top"><b>'.number_format($total, 2, '.', ',').'</b></td>
				</tr>
				<tr>
					<td valign="top"></td>
					<td valign="top"></td>
					<td valign="top"></td>
					<td valign="top"><b>Tax:</b></td>
					<td valign="top"><b>'.number_format(($order->price*$order->tax/100), 2, '.', ',').'</b></td>
				</tr>
				<tr>
					<td valign="top"></td>
					<td valign="top"></td>
					<td valign="top"></td>
					<td valign="top"><b>Discount:</b></td>
					<td valign="top"><b>-'.number_format(($order->price*$order->discount/100), 2, '.', ',').'</b></td>
				</tr>
				<tr>
					<td valign="top"></td>
					<td valign="top"></td>
					<td valign="top"></td>
					<td valign="top"><b>Grand Total:</b></td>
					<td valign="top"><b>'.number_format($grandtotal, 2, '.', ',').'</b></td>
				</tr>';
				
				if ($invoice->partial == 1) {
					$html .= '<tr>
						<td valign="top"></td>
						<td valign="top"></td>
						<td valign="top"></td>
						<td valign="top"><b>Required in advance:</b></td>
						<td valign="top"><b>'.number_format($order->preq, 2, '.', ',').'</b></td>
					</tr>';
				} else {
					$html .= '<tr>
					<td valign="top"></td>
					<td valign="top"></td>
					<td valign="top"></td>
					<td valign="top"><b>Already paid:</b></td>
					<td valign="top"><b>-'.number_format($paid, 2, '.', ',').'</b></td>
				</tr>
				<tr>
						<td valign="top"></td>
						<td valign="top"></td>
						<td valign="top"></td>
						<td valign="top"><b>Left to pay:</b></td>
						<td valign="top"><b>'.number_format($grandtotal - $paid, 2, '.', ',').'</b></td>
					</tr>';
				}
			}
		}
$html .= '</table>';
		if ($type == 1) {
			$html .= '
<p>Note:</p>
<ol>
	<li>Quotation valid for 2 weeks subject to availability of Buses</li>
	<li>No GST Chargeable</li>
	<li>1 week notice required before commencement of Services to facilitate Driver Orientation</li>
</ol>
<h2 align="center">THANK YOU FOR YOUR CONSIDERATION</h2>';
		}
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		$html = '<h1 align="center"><img src="'.FCPATH.'assets/images/bookabus.jpg" /></h1>
<h1 align="center">Invoice'.(($invoice->proforma == 1) ? ' Proforma' : '').'</h1>

<table style="border: 1px solid #09C; border-collapse: collapse;" valign="top" cellpadding="10" cellspacing="0" border="0" bordercolor="#CCCCCC" align="left" width="100%">	
	<tr bgcolor="#c3ebff">
		<td valign="top" style="border-top: 1px solid #09C; "><b>TO</b></td>
		<td valign="top" style="border-top: 1px solid #09C; "><b>FROM</b></td>
		<td valign="top" style="border-top: 1px solid #09C; "><b>Details</b></td>
	</tr>	
	<tr>
		<td valign="top">'.$clientname.'</td>
		<td valign="top">Book a Bus Pte Ltd</td>
		<td valign="top"></td>
	</tr>
	<tr>
		<td valign="top">'.$uinfo->email.'<br  />'.$uinfo->phone.'</td>
		<td valign="top">20 Bukit Batok Crescent<br  />09-07 Enterprise Centre<br  />Singapore 658080<br  />TEL: +65 6316 6350<br  />FAX: +65 6569 6166</td>
		<td valign="top">
			<b>DATE:</b> '.date('jS F Y', strtotime($date)).'<br  />
			<b>QUOTE ID:</b> '.$order->id.'<br  />
			<b>FOR:</b> Bus Services<br  />
			'.$terms.'
			'.$validity.'
			<b>REP:</b> Darren Lim<br  />
			<b>Mobile:</b> 94773707<br  />
			<b>e-mail:</b> darren@bookabus.sg<br  />
			'.$fieldsHTML.'
		</td>
	</tr>
</table>

<br />&nbsp;
<br />&nbsp;
<br />

<table  style="border: 1px solid #09C; border-collapse: collapse;" valign="top" cellpadding="10" cellspacing="0" border="0" bordercolor="#CCCCCC" align="left" width="100%">
	<tr bgcolor="#c3ebff">
		<td valign="top" width="100" style="border-top: 1px solid #09C; border-left: 1px solid #09C;"><b>ITEM</b></td>
		<td valign="top" width="366" style="border-top: 1px solid #09C; "><b>DESCRIPTION</b></td>
		<td valign="top" style="border-top: 1px solid #09C; "><b>DATE (TIME)</b></td>
		<td valign="top" style="border-top: 1px solid #09C; "><b>BUS TYPE</b></td>
		<td valign="top" width="109" style="border-top: 1px solid #09C; border-right: 1px solid #09C;"><b>'.(($type == 1) ? "AMOUNT, PER MONTH, SGD" : 'AMOUNT, SGD').'</b></td>
	</tr>';
	/*<tr style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;">
		<td valign="top">1</td>
		<td valign="top">Mo, Tu, We, Th, Fr</td>
		<td valign="top"></td>
		<td valign="top">19 Seater (1)</td>
		<td valign="top"></td>
	</tr>
	<tr style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;">
		<td valign="top"></td>
		<td valign="top">Pickup Location: Some address</td>
		<td valign="top">07:10</td>
		<td valign="top"></td>
		<td valign="top"></td>
	</tr>
	<tr style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;">
		<td valign="top"></td>
		<td valign="top">Pickup Location: Another address</td>
		<td valign="top">07:25</td>
		<td valign="top"></td>
		<td valign="top"></td>
	</tr>
	<tr style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;">
		<td valign="top"></td>
		<td valign="top">Drop Off Location: Third address</td>
		<td valign="top">08:00</td>
		<td valign="top"></td>
		<td valign="top"></td>
	</tr>
	<tr style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;">
		<td valign="top"></td>
		<td valign="top"></td>
		<td valign="top"></td>
		<td valign="top">Total (Item 1)</td>
		<td valign="top">2,400.00</td>
	</tr>
	<tr style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;">
		<td valign="top">2</td>
		<td valign="top">Mo, We, Fr</td>
		<td valign="top"></td>
		<td valign="top">19 Seater (1)</td>
		<td valign="top"></td>
	</tr>
	<tr style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;">
		<td valign="top"></td>
		<td valign="top">Pickup Location: Some address</td>
		<td valign="top">07:10</td>
		<td valign="top"></td>
		<td valign="top"></td>
	</tr>
	<tr style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;">
		<td valign="top"></td>
		<td valign="top">Pickup Location: Another address</td>
		<td valign="top">07:25</td>
		<td valign="top"></td>
		<td valign="top"></td>
	</tr>
	<tr style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;">
		<td valign="top"></td>
		<td valign="top">Drop Off Location: Third address</td>
		<td valign="top">08:00</td>
		<td valign="top"></td>
		<td valign="top"></td>
	</tr>
	<tr style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;">
		<td valign="top"></td>
		<td valign="top"></td>
		<td valign="top"></td>
		<td valign="top">Total (Item 2)</td>
		<td valign="top">2,400.00</td>
	</tr>
	<tr style="border-top: 1px solid #09C; border-bottom: 1px solid #09C; font-size: 20px;" bgcolor="#61c6d8">
		<td valign="top"></td>
		<td valign="top"></td>
		<td valign="top"></td>
		<td valign="top"><b>Grand Total:</b></td>
		<td valign="top"><b>4,800.00</b></td>
	</tr>*/
		if ($type == 1) {
			//recurring
			$routes = json_decode($order->routes);
			$c = 1;
			foreach ($routes as $route) {
				for ($i = 0; $i < count($route->weekdays); $i++) {
					$route->weekdays[$i] = substr($route->weekdays[$i], 0, 2);
				}
				$html .= '<tr style="border-top: 1px solid #09C; ">
					<td valign="top" style="border-top: 1px solid #09C; ">'.$c.'</td>
					<td valign="top" style="border-top: 1px solid #09C; ">'.implode(', ', $route->weekdays).'</td>
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; ">'.$route->bustype.'</td>
					<td valign="top" style="border-top: 1px solid #09C; "></td>
				</tr>';
				
				// locations
				foreach ($route->pickup as $pickup) {
					$html .= '<tr style="border-top: 1px solid #09C; ">
						<td valign="top" style="border-top: 1px solid #09C; "></td>
						<td valign="top" style="border-top: 1px solid #09C; ">Pickup Location: '.$pickup->location.'</td>
						<td valign="top" style="border-top: 1px solid #09C; ">'.$pickup->time.'</td>
						<td valign="top" style="border-top: 1px solid #09C; "></td>
						<td valign="top" style="border-top: 1px solid #09C; "></td>
					</tr>';
				}
				foreach ($route->dropoff as $dropoff) {
					$html .= '<tr style="border-top: 1px solid #09C; ">
						<td valign="top" style="border-top: 1px solid #09C; "></td>
						<td valign="top" style="border-top: 1px solid #09C; ">Drop Off Location: '.$dropoff->location.'</td>
						<td valign="top" style="border-top: 1px solid #09C; ">'.$dropoff->time.'</td>
						<td valign="top" style="border-top: 1px solid #09C; "></td>
						<td valign="top" style="border-top: 1px solid #09C; "></td>
					</tr>';
				}
				
				$html .= '<tr style="border-top: 1px solid #09C; ">
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; ">Total (Item '.$c.')</td>
					<td valign="top" style="border-top: 1px solid #09C; ">'.number_format($route->price, 2, '.', ',').'</td>
				</tr>';
				
				$c++;
			}
			
			$html .= '<tr style="border-top: 1px solid #09C;  font-size: 45px;" bgcolor="#61c6d8">
				<td valign="top" style="border-top: 1px solid #09C; border-left: 1px solid #09C; border-bottom: 1px solid #09C;"></td>
				<td valign="top" style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;"></td>
				<td valign="top" style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;"></td>
				<td valign="top" style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;"><b>Grand Total:</b></td>
				<td valign="top" style="border-top: 1px solid #09C; border-right: 1px solid #09C; border-bottom: 1px solid #09C;"><b>'.number_format($order->total_price, 2, '.', ',').'</b></td>
			</tr>';
		} elseif ($type == 2) { // cancellation fee
			$html .= '<tr style="border-top: 1px solid #09C; ">
					<td valign="top" style="border-top: 1px solid #09C; ">1</td>
					<td valign="top" style="border-top: 1px solid #09C; ">Cancelation fee</td>
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; ">'.number_format($order->cancelfee, 2, '.', ',').'</td>
				</tr>';
			
			$html .= '<tr style="border-top: 1px solid #09C;  font-size: 45px;" bgcolor="#61c6d8">
				<td valign="top" style="border-top: 1px solid #09C; border-left: 1px solid #09C; border-bottom: 1px solid #09C;"></td>
				<td valign="top" style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;"></td>
				<td valign="top" style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;"></td>
				<td valign="top" style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;"><b>Grand Total:</b></td>
				<td valign="top" style="border-top: 1px solid #09C; border-right: 1px solid #09C; border-bottom: 1px solid #09C;"><b>'.number_format($order->cancelfee, 2, '.', ',').'</b></td>
			</tr>';
		} else {
			// jobs
			$c = 0;
			$j = $this->getOrderJobs($order->gid);
			foreach ($j as $job) {
				$c++;
				if ($job->job_type == 0 || $job->job_type == 1) {
					$html .= '<tr style="border-top: 1px solid #09C; ">
						<td valign="top" style="border-top: 1px solid #09C; ">'.$c.'</td>
						<td valign="top" style="border-top: 1px solid #09C; ">'.nl2br($this->Jobs->formatJobInfo($job)).'</td>
						<td valign="top" style="border-top: 1px solid #09C; ">'.(($job->job_type == 1) ? "Time Based" : "Trip Based").'</td>
						<td valign="top" style="border-top: 1px solid #09C; "></td>
						<td valign="top" style="border-top: 1px solid #09C; "></td>
					</tr>';
				}
			}
			
			// Price changes
			//if ($invoice->proforma != 1) {
				$this->db->where('jid', $order->gid);
				$qc = $this->db->get('price_changes');
				$changes = $qc->result();
				foreach ($changes as $change) {
					$reason = ($change->amount{0} == "-") ? "Price decrease: " : "Price increase: ";
					$reason .= $change->reason;
					$html .= '<tr style="border-top: 1px solid #09C; ">
						<td valign="top" style="border-top: 1px solid #09C; ">'.$c.'</td>
						<td valign="top" style="border-top: 1px solid #09C; ">'.$reason.'</td>
						<td valign="top" style="border-top: 1px solid #09C; "></td>
						<td valign="top" style="border-top: 1px solid #09C; "></td>
						<td valign="top" style="border-top: 1px solid #09C; ">'.number_format(str_replace(array('-', '+'), '', $change->amount), 2, '.', ',').'</td>
					</tr>';
					
					$c++;
				}
			//}
			
			if ($type == 1) {
				$html .= '<tr style="border-top: 1px solid #09C;  font-size: 45px;" bgcolor="#61c6d8">
					<td valign="top" style="border-top: 1px solid #09C; border-left: 1px solid #09C; border-bottom: 1px solid #09C;"></td>
					<td valign="top" style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;"></td>
					<td valign="top" style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;"></td>
					<td valign="top" style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;"><b>Grand Total:</b></td>
					<td valign="top" style="border-top: 1px solid #09C; border-right: 1px solid #09C; border-bottom: 1px solid #09C;"><b>'.number_format($order->price + ($order->price*$order->tax/100) - ($order->price*$order->discount/100), 2, '.', ',').'</b></td>
				</tr>';
			} else {
				$total = $order->price;
				$grandtotal = $order->price + ($order->price*$order->tax/100) - ($order->price*$order->discount/100);
				$paid = $order->paid;
				$html .= '<tr style="border-top: 1px solid #09C; ">
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; "><b>Total:</b></td>
					<td valign="top" style="border-top: 1px solid #09C; "><b>'.number_format($total, 2, '.', ',').'</b></td>
				</tr>
				<tr style="border-top: 1px solid #09C; ">
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; "><b>Tax:</b></td>
					<td valign="top" style="border-top: 1px solid #09C; "><b>'.number_format(($order->price*$order->tax/100), 2, '.', ',').'</b></td>
				</tr>
				<tr style="border-top: 1px solid #09C; ">
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; "><b>Discount:</b></td>
					<td valign="top" style="border-top: 1px solid #09C; "><b>-'.number_format(($order->price*$order->discount/100), 2, '.', ',').'</b></td>
				</tr>
				<tr style="border-top: 1px solid #09C;  font-size: 45px;" bgcolor="#61c6d8">
					<td valign="top" style="border-top: 1px solid #09C; border-left: 1px solid #09C;"></td>
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; "><b>Grand Total:</b></td>
					<td valign="top" style="border-top: 1px solid #09C; border-right: 1px solid #09C;"><b>'.number_format($grandtotal, 2, '.', ',').'</b></td>
				</tr>';
				
				if ($invoice->partial == 1) {
					$html .= '<tr style="border-top: 1px solid #09C; ">
						<td valign="top" style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;"></td>
						<td valign="top" style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;"></td>
						<td valign="top" style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;"></td>
						<td valign="top" style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;"><b>Required in advance:</b></td>
						<td valign="top" style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;"><b>'.number_format($order->preq, 2, '.', ',').'</b></td>
					</tr>';
				} else {
					$html .= '<tr style="border-top: 1px solid #09C; ">
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; "></td>
					<td valign="top" style="border-top: 1px solid #09C; "><b>Already paid:</b></td>
					<td valign="top" style="border-top: 1px solid #09C; "><b>-'.number_format($paid, 2, '.', ',').'</b></td>
				</tr>
				<tr style="border-top: 1px solid #09C;  font-size: 45px;" bgcolor="#61c6d8">
						<td valign="top" style="border-top: 1px solid #09C; border-left: 1px solid #09C; border-bottom: 1px solid #09C;"></td>
						<td valign="top" style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;"></td>
						<td valign="top" style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;"></td>
						<td valign="top" style="border-top: 1px solid #09C; border-bottom: 1px solid #09C;"><b>Left to pay:</b></td>
						<td valign="top" style="border-top: 1px solid #09C; border-right: 1px solid #09C; border-bottom: 1px solid #09C;"><b>'.number_format($grandtotal - $paid, 2, '.', ',').'</b></td>
					</tr>';
				}
			}
		}
$html .= '</table>';
		if ($type == 1) {
			$html .= '
<p>Note:</p>
<ol>
	<li>Quotation valid for 2 weeks subject to availability of Buses</li>
	<li>No GST Chargeable</li>
	<li>1 week notice required before commencement of Services to facilitate Driver Orientation</li>
</ol>
<h2 align="center">THANK YOU FOR YOUR CONSIDERATION</h2>';
		}
		
		$pdf->writeHTML($html, true, false, true, false, '');
		$pdf->lastPage();
		
		$pdf->Output('invoice.pdf', 'I');
	}
}
?>